#!/usr/bin/python2.4

"""Generate list of active torrents.

Originally part of the open-tracker project (http://code.google.com/p/open-tracker/),
modified to work with torrent-tracker.
"""

__author__ = 'allen@thebends.org (Allen Porter) and gavinandresen@gmail.com (Gavin Andresen)'

import datetime
import os
import wsgiref.handlers
import sys
import urllib

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import model

MAX_DOWNLOAD_SIZE = 10000000  # 10 million bytes, safely smaller than GAE 10MB limit

class MainPage(webapp.RequestHandler):

  def _size(self, torrent):
    if 'length' in torrent.info: return torrent.info['length']
    return sum(f['length'] for f in torrent.info['files'])

  def _links(self, torrent):
    root_url = 'http://'+os.environ['HTTP_HOST']
    hashHex = torrent.key().name()
    links = [ { 'type' : 'Torrent',  'url' : '%s/seed/%s.torrent'%(root_url,hashHex) } ]
    if 'length' in torrent.info and torrent.info['length'] < MAX_DOWNLOAD_SIZE:
      links.append( { 'type' : 'HTTP', 'url' : '%s/seed/%s/%s'%(root_url,hashHex,urllib.quote(torrent.name))})
    return links

  def _deleteLink(self,torrent):
    root_url = 'http://'+os.environ['HTTP_HOST']
    hashHex = torrent.key().name()
    return '%s/delete/%s'%(root_url,hashHex)

  def get(self):
    query = model.Torrent.all().order('-date')
    if not self.request.get('showincomplete'):
      query.filter("complete =", True)
    torrents = query.fetch(1000)
    for torrent in torrents:
      torrent.links = self._links(torrent)
      torrent.delete_url = self._deleteLink(torrent)
      torrent.size = self._size(torrent)

    template_values = {
      'is_current_user_admin' : users.is_current_user_admin(),
      'torrents': torrents,
      }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication(
    [ ( '/', MainPage ) ],
    debug=True)

wsgiref.handlers.CGIHandler().run(application)
